package com.abiao.shop.service;

import com.abiao.shop.pojo.User;
import com.abiao.shop.redis.RedisService;
import com.abiao.shop.redis.SnapKey;
import com.abiao.shop.result.CodeMsg;
import com.abiao.shop.vojo.GoodsVo;
import com.abiao.shop.vojo.OrderVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @Description: SnapService    秒杀业务操作类
 * @Author: AB
 * @Date: 2021-07-17
 * @Version:v1.0
 */
@Service
public class SnapService {

    @Autowired
    OrderService orderService;
    @Autowired
    GoodsService goodsService;
    @Autowired
    RedisService redisService;

    /**
     * 秒杀主体方法，减库存，下订单，写入秒杀订单
     * @param user
     * @param goodsVo
     * @return
     */
    @Transactional
    public OrderVo snapping(User user, GoodsVo goodsVo) {
        boolean success = goodsService.reduceStock(goodsVo);
        if (success){
            return orderService.createOrder(user,goodsVo);
        }else {
            setGoodsOver(goodsVo.getId());
            return null;
        }
    }
    /**
     * 获取秒杀结果
     * @param userId
     * @param goodsId
     * @return
     */
    public Object getSnapResult(long userId, long goodsId){
        OrderVo order = orderService.getOrderByGoodsIdUserId(userId,goodsId);
        if (order != null){
            return order;   //success
        }else{
            boolean isOver = getGoodsOver(goodsId);
            if (isOver){
                return CodeMsg.STOCK_ZERO;
            }else {
                return CodeMsg.ON_QUEUE;   //排队中
            }
        }
    }

    //设置商品是否卖完
    public void setGoodsOver(long goodsId){
        redisService.set(SnapKey.IS_GOODS_OVER,""+goodsId,true);
    }
    public boolean getGoodsOver(long goodsId){
        return redisService.exists(SnapKey.IS_GOODS_OVER,""+goodsId);
    }
}
